package com.txy.test.domain.strategy.service.raffle;

import com.alibaba.fastjson.JSON;
import com.txy.domain.strategy.service.IRaffleService;
import com.txy.domain.strategy.model.entity.RaffleAwardEntity;
import com.txy.domain.strategy.model.entity.RaffleFactorEntity;
import com.txy.domain.strategy.service.armory.IStrategyArmory;
import com.txy.domain.strategy.service.rule.chain.impl.RuleWeightLogicChain;
import com.txy.domain.strategy.service.rule.tree.impl.RuleLockLogicTreeNode;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;

import javax.annotation.Resource;
import java.util.concurrent.CountDownLatch;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class DefaultRaffleServiceImplTest {
    @Resource
    private IRaffleService defaultRaffleService;

    @Resource
    private IStrategyArmory strategyArmory;

    @Resource
    private RuleWeightLogicChain ruleWeightLogicFilter;

    @Resource
    private RuleLockLogicTreeNode ruleLockLogicTreeNode;

    @Before
    public void test_assembleLotteryStrategy() {
        strategyArmory.assembleLotteryStrategy(100006L);

        ReflectionTestUtils.setField(ruleWeightLogicFilter, "userScore", 4500L);
        ReflectionTestUtils.setField(ruleLockLogicTreeNode, "userRaffleCount", 200);
    }

    @Test
    public void test() {
        RaffleFactorEntity raffleFactorEntity = RaffleFactorEntity.builder()
                .userId("txy")
                .strategyId(100001L).build();
        RaffleAwardEntity raffleAwardEntity = defaultRaffleService.performRaffle(raffleFactorEntity);
        log.info(raffleAwardEntity.toString());
    }

    @Test
    public void test_ruleLock() {
        RaffleFactorEntity raffleFactorEntity = RaffleFactorEntity.builder()
                .userId("txy")
                .strategyId(100003L).build();
        RaffleAwardEntity raffleAwardEntity = defaultRaffleService.performRaffle(raffleFactorEntity);
        log.info(raffleAwardEntity.toString());
    }

    // 责任链 redis库存扣减
    @Test
    public void test_raffleAward() throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            RaffleAwardEntity raffleAwardEntity = defaultRaffleService.performRaffle(RaffleFactorEntity.builder()
                    .strategyId(100006L)
                    .userId("txy").build());

            log.info("raffle result: {}", JSON.toJSONString(raffleAwardEntity.toString()));
        }
        new CountDownLatch(1).await();
    }
}
